import jwt
from flask import current_app
from datetime import datetime, timedelta


def generate_token(payload, expiry, algorithm='HS256'):
    """生成token"""
    key = current_app.config.get("SECRET_KEY")
    if 'exp' not in payload:
        payload['exp'] = expiry
    try:
        token = jwt.encode(payload,key,algorithm)
        return token
    except Exception as e:
        print('generate_token error>>>', e)
        return e


def check_token(token):
   #  校验token
   key = current_app.config.get("SECRET_KEY")
   # jwt.decode(token)
   print(token,key)
   payload = jwt.decode(token,key,algorithms=['HS256'])
   return payload


def _generate_token(payload, is_refresh=True):
    # 设置有效期, 第一默认生成2个小时的有效期
    expiry = datetime.now() + timedelta(seconds=30)
    token = generate_token(payload, expiry)
    # 默认需要刷新生成token
    if is_refresh:
        # 刷新生成的token,有效期15天
        expiry = datetime.now() + timedelta(days=15)
        # 给payload 添加刷新token的标识
        payload.update({'is_refresh':True})
        print("jwt util payload--->", payload)
        refresh_token = generate_token(payload, expiry)
    else:
        refresh_token = None
    return token, refresh_token


























